package com.jzoom.zoom.excel;

import com.jzoom.zoom.common.io.Io;
import com.jzoom.zoom.common.utils.DataObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class ExcelResultSet implements Iterable<DataObject>, Iterator<DataObject> {
	String[] keys;
	
	HSSFWorkbook hwb;
	//这里进行创建excel
	HSSFSheet sheet;
	
	private int rows;
	private int currentRow;
	
	private HSSFRow recentRow;
	
	
	private String sheetName;
	
	public String[] keys(){
		return keys;
	}
	
	public ExcelResultSet(File file) throws FileNotFoundException, ExcelParseError{
		FileOutputStream out = null;
		try{
			hwb = new HSSFWorkbook(new FileInputStream(file));
			read(0);
		} catch (IOException e) {
			throw new ExcelParseError(e);
		}finally{
			Io.close(out);
		}
	}
	
	
	public void read(int index){
		sheet = hwb.getSheetAt(index);
		currentRow =1;
		//第一行
		HSSFRow row = sheet.getRow(0);
		sheetName = sheet.getSheetName();
		if(row==null){
			rows = 0;
			return;
		}
		int max = row.getLastCellNum();
		keys = new String[max];
		rows = sheet.getLastRowNum();
		for( int i = 0; i <max	; ++i ){
			HSSFCell cell = row.getCell(i);
			keys[i] = cell.getStringCellValue();
		}
	}
	
	public void close(){
		if(hwb!=null){try{hwb.close();}catch(Exception e){}}
	}
	
	public boolean hasNext(){
		return currentRow <= rows;
	}
	
	public DataObject next(){
		recentRow = sheet.getRow(currentRow++);
		DataObject record = new DataObject(new LinkedHashMap<String, Object>());
		int index=  0;
		for (String string : keys) {
			record.put(string, ExcelUtil.getCellFormatValue( recentRow.getCell(index) ) );
			++index;
		}
		
		return record;
	}

	public String getSheetName() {
		return sheetName;
	}

	public void setSheetName(String sheetName) {
		this.sheetName = sheetName;
	}

	@Override
	public Iterator<DataObject> iterator() {
		
		return this;
	}

	
	public void remove() {
		
	}
	
	
	
	
	
	
}
